package com.cpr.demo.interceptor;

import com.cpr.demo.constant.RedisKeyConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Chen Panrui
 * created at 2021/8/31 16:22
 * 用另外一个 {@link com.cpr.demo.filter.RedisCountFilter} 代替这个统计访问量-功能
 * Q:为什么不用拦截器做统计访问量的功能？
 * A:因为统计不了用户随意输入的url走不到这个拦截器。
 */
@Component
@ConditionalOnClass(HttpServletRequest.class)
@RequiredArgsConstructor
@Slf4j
@Deprecated
public class RedisCountInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    @Value("${spring.application.name}")
    private String applicationName;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String url = request.getRequestURL().toString();
            String[] split = url.split(applicationName);
            Long count = stringRedisTemplate.boundHashOps(RedisKeyConstant.VISITOR_COUNT).increment(split[1], 1L);
            log.info("访问次数{}--{}", split[1], count);
        } catch (Exception e){
            log.info("记录访问次数异常", e);
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
